package cn.knightzz.config;

import cn.knightzz.auth.*;
import cn.knightzz.filter.CustomAuthenticationFilter;
import cn.knightzz.filter.JwtAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author knightzz
 * @date 2021/4/8 10:42
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);

    // 加密对象
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserDetailsService userDetailsService;

    /**
     * 登陆成功的处理方案
     */
    @Resource
    MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    /**
     * 登陆失败的处理方案
     */

    @Resource
    MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    /**
     * 匿名用户访问无权限资源时的异常
     */
    @Resource
    MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    /**
     * 权限不足处理方案
     */
    @Resource
    private MyAccessDeniedHandler myAccessDeniedHandler;

    /**
     * 超时管理
     */
    @Resource
    private MyInvalidSessionStrategy myInvalidSessionStrategy;

    /**
     * 注销操作处理器
     */
    @Resource
    private MyLogoutHandler myLogoutHandler;

    /**
     * 注销成功处理器
     */
    @Resource
    private MyLogoutSuccessHandler myLogoutSuccessHandler;

    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        logger.info("进入授权 =>>>>>>>>>>>>>>>>>>>>>>");
        http.authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/users/**").permitAll()
                .antMatchers("/roles/**").permitAll()
                .antMatchers("/file/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                // 允许注销操作
                .logout().permitAll()
                //添加注销操作处理器
                .addLogoutHandler(myLogoutHandler)
                //注销成功的处理方案
                .logoutSuccessHandler(myLogoutSuccessHandler)
                //登出之后删除cookie
                .deleteCookies("JSESSIONID")
                .and()
                .formLogin().loginPage("/login")
                //登录表单form中action的地址，也就是处理认证请求的路径
                .loginProcessingUrl("/login")
                //登录表单form中用户名输入框input的name名，不修改的话默认是username
                .usernameParameter("username")
                //登录表单form中密码输入框input的name名，不修改的话默认是password
                .passwordParameter("password")
                //登录认证成功后默认转跳的路径  注意这里不要忘记加permitAll()
                .defaultSuccessUrl("/home").permitAll()
                .successHandler(myAuthenticationSuccessHandler)
                .failureHandler(myAuthenticationFailureHandler)
                .and()
                // 设置出现异常的情况下的处理器
                .exceptionHandling()
                // 权限不足的处理方案
                .accessDeniedHandler(myAccessDeniedHandler)
                // 未登录状态去访问需要权限才能访问的资源时异常
                .authenticationEntryPoint(myAuthenticationEntryPoint)
                .and()
                //无状态的,任何时候都不会使用session
                .sessionManagement().invalidSessionStrategy(myInvalidSessionStrategy);


        // post 请求必须验证csrf 否则就会出现 403
        http.csrf().disable();
        // 配置JSON格式的用户名和密码获取
        http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        // 配置jwt拦截器
        http.addFilter(jwtAuthenticationFilter());
    }
    // jwt拦截器
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JwtAuthenticationFilter(authenticationManagerBean());
    }

    //注册自定义的UsernamePasswordAuthenticationFilter
    @Bean
    CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
        // 登陆成功的情况下的处理器
        filter.setAuthenticationSuccessHandler(new MyAuthenticationSuccessHandler());
        //filter.setAuthenticationFailureHandler(new FailureHandler());
        //filter.setFilterProcessesUrl("/login/self");
        //这句很关键，重用WebSecurityConfigurerAdapter配置的AuthenticationManager，不然要自己组装AuthenticationManager
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }

    // 授权
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }
}
